package com.example.netty.nbcb.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

/**
 * <p></p>
 *
 * @author xin
 * @version 2023/11/2 16:39
 **/
public class NormalNBCBServerHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(NormalNBCBServerHandler.class);


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.debug("收到客户端消息");
        try {
            ByteBuf buf = (ByteBuf) msg;
            byte[] req = new byte[buf.readableBytes()];
            buf.readBytes(req);
            String body = new String(req, StandardCharsets.UTF_8);
            System.out.println("-----start------|\n  " + body + " \n | ------end------");

            //发送给客户端
            for (int n = 0; n < 5; n++) {
                String serverMsg = "++++++++我是服务端给客户端的消息 【" + n + "】+++++++\n";
                // 初始化 容量，默认是1024
                ByteBuf serverBuffer = ctx.alloc().buffer(16);
                serverBuffer.writeBytes(serverMsg.getBytes(StandardCharsets.UTF_8));
                // 此处演示粘包现象，连续发送了多次，客户端将多次请求合并接收，可以看接收的序号
                ctx.channel().writeAndFlush(serverBuffer);
            }
        } catch (Exception e) {
            logger.error("接收数据异常", e);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
